#pragma once

#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port)
        : _port(port),
          _listensocketptr(std::make_unique<TcpSocket>()),
          _isrunning(false)
    {
        _listensocketptr->BuildTcpSocketMethod(_port);
    }

    void Start(ioservice_t callback)
    {
        _isrunning = true;

        while (_isrunning)
        {
            InetAddr client;
            auto sock = _listensocketptr->Accept(&client);
            if (sock == nullptr)
            {
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success..." << client.StringAddr();

            pid_t id = fork();
            if (id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error...";
                exit(FORK_ERR);
            }
            else if (id == 0)
            {
                _listensocketptr->Close();
                if (fork() > 0)
                    exit(OK);
                callback(sock, client);
                sock->Close();
                exit(OK);
            }
            else
            {
                sock->Close();
                pid_t rid = ::waitpid(id, nullptr, 0);
                (void)rid;
            }
        }

        _isrunning = false;
    }

    ~TcpServer() {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocketptr;
    bool _isrunning;
};
